package com.itljm.cxrMarket.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itljm.cxrMarket.common.PageResult;
import com.itljm.cxrMarket.common.Result;
import com.itljm.cxrMarket.entity.Articles;
import com.itljm.cxrMarket.service.ArticlesService;
import io.micrometer.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author ljm
 * @date 2024/12/20 10:16
 */
@RestController
@RequestMapping("/articles")
@CrossOrigin
public class ArticlesController {
    @Autowired
    private ArticlesService articlesService;

    // 分页查询文章信息
    @RequestMapping("/info")
    public PageResult<Articles> selectArticlesByPage(Integer page, Integer limit, String title, String categoryId) {
        if (page == null) {
            page = 0;
        }
        if (limit == null) {
            limit = 15;
        }

        Page<Articles> articlePage = new Page<>(page, limit);

        QueryWrapper<Articles> wrapper = new QueryWrapper<>();

        if (StringUtils.isNotBlank(title)) {
            wrapper.like("title", title);
        }
        if (StringUtils.isNotBlank(categoryId)) {
            wrapper.eq("category_id", categoryId);
        }

        List<Articles> articles = articlesService.selectArticlesByPage(articlePage, wrapper);

        // 返回分页结果
        return new PageResult<>(articles, articlePage.getTotal());
    }

    // 根据文章ID查询文章信息
    @RequestMapping("/info/{id}")
    public Result selectArticleById(@PathVariable Integer id) {
        Articles articles = articlesService.selectArticleById(id);
        if (articles == null) {
            return Result.fail("文章不存在");
        }
        return Result.ok(articles);
    }

    // 新增或更新文章信息
    @RequestMapping("/save")
    public Result saveArticle(@RequestBody Articles articles) {
        boolean b = articlesService.saveOrUpdateArticle(articles);
        if (articles.getArticleId() == null&&b){
            return Result.ok("新增成功");
        }else {
            return Result.ok("修改成功");
        }
    }

    // 删除文章信息
    @RequestMapping("/delete/{id}")
    public Result deleteArticle(@PathVariable Integer id) {
        boolean b = articlesService.removeArticleById(id);
        if (b) {
            return Result.ok("操作成功");
        }
        return Result.fail("操作失败");
    }

}
